const express = require('express')
const path = require('path')
const ApiRes = require('./common/apiRes')
const { app } = require('electron');
const multer = require('multer');
const usePrinterRouter = require('./router/printer')
const usePrintRouter = require('./router/print')
const usePrintLogRouter = require('./router/printLog')
const useTtsRouter = require('./router/tts')

const useImagesRouter = require('./router/images')

const useFontsRouter = require('./router/fonts')
const useRetailReport = require('./router/retailReport')

const { HTTP_PORT,WWW_PATH } = require('../tools/helper')

class WebHttp {
    static _app = null
    static _server = null
    constructor() {
    }
    static start() {
        this._app = express()
        // 设置跨域允许所有都能访问
        this._app.use((req, res, next) => {
            res.header('Access-Control-Allow-Origin', '*')
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
            res.setHeader("Access-Control-Max-Age", "3600"); // 1小时内无需再次预检
            if (req.method === 'OPTIONS') {
                res.sendStatus(204);
                return;
            }
            next()
        })

        // 设置允许的请求体最大为 10MB（可根据需要调整）
        this._app.use(express.json({ limit: '50mb' }));
        this._app.use(express.urlencoded({ limit: '50mb', extended: true }));



        // JSON解析
        this._app.use(express.json())
        // URL编码表单解析
        this._app.use(express.urlencoded({ extended: true }))
        // Multipart表单数据处理
        const upload = multer({
            dest: path.join(app.getAppPath(), '..', 'temp/uploads'),
            limits: {
                fieldSize: 50 * 1024 * 1024  // 设置单个字段最大为 50MB，根据需要调整
            }
        });
        this._app.use(upload.none()); // 只处理非文件字段
        // 静态资源
        this._app.use(express.static(WWW_PATH));

        // 添加请求日志中间件
        this._app.use((req, res, next) => {
            console.log(`${new Date().toISOString()} ${req.method} ${req.url}`)
            next()
        })

        this.initRouter()
        this._server = this._app.listen(HTTP_PORT, () => {
            console.log(`HTTP server is running on port ${HTTP_PORT}`)
        })
    }

    static initRouter() {
        // 根路由 - 返回 index.html
        this._app.get('/', (req, res) => {
            res.sendFile(path.join(WWW_PATH, 'index.html'));
        });

        // 打印机路由
        this._app.use('/printer', usePrinterRouter)
        // 打印路由
        this._app.use('/print', usePrintRouter)
        // 打印日志路由
        this._app.use('/printLog', usePrintLogRouter)

        // TTS路由
        this._app.use('/tts', useTtsRouter)
        // 图片路由
        this._app.use("/images", useImagesRouter)
        // 字体下载
        this._app.use("/fonts", useFontsRouter)
        this._app.use("/retailReport", useRetailReport)

        // 错误处理中间件
        this._app.use((err, req, res, next) => {
            console.error('服务器错误:', err)
            ApiRes.fail(res, '服务器内部错误', err.message)
        })

        // 处理 404
        this._app.use((req, res) => {
            ApiRes.fail(res, '未找到请求的资源')
        })
    }

    static stop() {
        if (this._server) {
            this._server.close()
            this._server = null
            console.log('HTTP server stopped')
        }
    }
}

module.exports = WebHttp